package com.albb.config;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.sql.Time;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @Title:
 * @BelongProjecet Day416yk
 * @BelongPackage com.albb.config
 * @Description:
 * @Copyright 研发一部
 * @Author: 马召茹
 * @Date: 2024/4/16 17:27
 * @Version V1.0
 */
@Configuration
public class Config implements GlobalFilter {

    @Value("${url}")
    public String url;

    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
       //获取路径
        String string = request.getPath().toString();
        String[] split = url.split(",");
        if (string.contains(split[0]) || string.contains(split[1])){
            return chain.filter(exchange);
        }
        String token = request.getHeaders().getFirst("token");
        if (token==null){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        Claims mtxc = Jwts.parser().setSigningKey("mtxc").parseClaimsJws(token).getBody();
        Integer id = (Integer) mtxc.get("id");
        //是否已经30分钟没有操作了
        String s = stringRedisTemplate.opsForValue().get("token" + id);
        if (s==null){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //若用户不间断执行操作，则自动续期
        Boolean expire = stringRedisTemplate.expire("token" + id, 30, TimeUnit.MINUTES);
        //是否异地登录
        if (!s.equals(token)){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        return chain.filter(exchange);
    }
}
